package com.reconcile.phone.web.controller.call;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reconcile.phone.common.core.controller.BaseController;
import com.reconcile.phone.common.core.domain.PageQuery;
import com.reconcile.phone.common.core.domain.R;
import com.reconcile.phone.common.core.domain.entity.SysUser;
import com.reconcile.phone.common.utils.WxUtil;
import com.reconcile.phone.system.service.ISysUserService;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序-用户管理
 * <p>
 * Author: liuliyou
 * Date: 2025/3/7
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/supermarket/mobile/user")
public class CUserController extends BaseController {

    private final ISysUserService sysUserService;

    /**
     * 获取邀请码(返回图片)
     *
     * @return 结果
     */
    @GetMapping("/getMyInvitationCode")
    public void getMyInvitationCode(HttpServletResponse response) throws IOException {
        //获取二维码
        String text = sysUserService.getMyInvitationCode().get("myInvitationCode").toString();
        // 自定义二维码设置
        QrConfig config = new QrConfig(300, 300);
        config.setMargin(2);  // 设置边距
        config.setForeColor(Color.BLACK);  // 前景色（二维码颜色）
        config.setBackColor(Color.WHITE);  // 背景色
        config.setErrorCorrection(ErrorCorrectionLevel.M);  // 设置纠错级别
        // 直接写入响应流（适合下载场景）
        QrCodeUtil.generate(text, config, "png", response.getOutputStream());
    }

    /**
     * 获取邀请码（返回access_token和字符串码）
     *
     * @return 结果
     */
    @GetMapping("/getMyInvitationCodeAndAccessToken")
    public R<Map<String, Object>> getMyInvitationCodeAndAccessToken(HttpServletResponse response) throws IOException {
        Map<String, Object> ajax = new HashMap<>();
        //获取邀请码
        String text = sysUserService.getMyInvitationCode().get("myInvitationCode").toString();
        ajax.put("code", text);
        //获取access_token
        String accessToken = WxUtil.xcxGetAccessToken();
        ajax.put("access_token", accessToken);
        return R.ok(ajax);
    }

    /**
     * 我的粉丝
     *
     * @param pageQuery
     * @return
     */
    @GetMapping("/myFans")
    public R<Page<SysUser>> myFans(PageQuery pageQuery) {
        return R.ok(sysUserService.myFans(pageQuery));
    }

    /**
     * 我的粉丝数
     *
     * @return
     */
    @GetMapping("/myFansNum")
    public R<Long> myFansNum() {
        return R.ok(sysUserService.myFansNum());
    }
}
